package com.wwwarehouse.usercenter.fragment.register;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.keyboard.VirtualKeyboardView;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.CheckUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.common.UserCenterCommon;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by xiaoke.ni on 2017/8/11.
 */
public class RCBindingFragment extends RegisterCardBaseFragment implements View.OnClickListener, TextWatcher, View.OnFocusChangeListener, ClearEditText.onMyFocusChangeListener {
    private View          mRootView;
    private ClearEditText mPhoneEdt;
    private ClearEditText mCodeEdt;
    private ClearEditText mEmailEdt;
    private TextView      mBindingTxt;

    private Button    mSubmitBtn;
    private TextView  mTvVerficode;
    private TextView  mTvBindLink;
    private TimeCount mTimeCount;
    private boolean isEle   = true;
    private boolean isEmail = true;//用于放置颜色的改变
    private TextInputLayout     mTilPhone;
    private TextInputLayout     mTilCode;
    private TextInputLayout     mTilEmail;
    private Map                 mMailmap;
    private RelativeLayout      mRlElse;
    private View                mViewCode;
    private View                mViewEmail;
    private VirtualKeyboardView mNumKeyboard;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_rc_binding1, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    private void initView() {
        mNumKeyboard = findView(mRootView, R.id.number);
        if (mNumKeyboard != null) {
            mNumKeyboard.setOnConfirmListener(new VirtualKeyboardView.OnConfirmListener() {
                @Override
                public void confirm() {
                    mNumKeyboard.setVisibility(View.INVISIBLE);
                }
            });
        }
        mRlElse = findView(mRootView, R.id.rl_else);
        mRlElse.setOnClickListener(this);
        mPhoneEdt = findView(mRootView, R.id.et_phone);//电话
        mPhoneEdt.setOnClickListener(this);
        mTilPhone = findView(mRootView, R.id.til_phone);

        mCodeEdt = findView(mRootView, R.id.et_code);//验证码
        mCodeEdt.setOnClickListener(this);
        hideSystemKeyboard(mPhoneEdt, mCodeEdt);
        mTilCode = findView(mRootView, R.id.til_code);
        mViewCode = findView(mRootView, R.id.view_code);
        mTvVerficode = findView(mRootView, R.id.tv_verificode);//点击获取验证码
        mTvVerficode.setOnClickListener(this);
        mEmailEdt = findView(mRootView, R.id.et_email);//邮箱
        mEmailEdt.setOnClickListener(this);
        mTilEmail = findView(mRootView, R.id.til_email);
        mViewEmail = findView(mRootView, R.id.view_email);
        //        mTvBindLink = findView(mRootView, R.id.tv_bindlink);//给邮箱发送邮件
        //        mTvBindLink.setOnClickListener(this);
        mBindingTxt = findView(mRootView, R.id.tv_binding);
        mBindingTxt.setOnClickListener(this);
        mBindingTxt.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线

        mSubmitBtn = findView(mRootView, R.id.btn_submit);


    }

    private void hideSystemKeyboard(EditText... mNumber) {
        for (int i = 0; i < mNumber.length; i++) {
            // 设置不调用系统键盘
            if (android.os.Build.VERSION.SDK_INT <= 10) {
                mNumber[i].setInputType(InputType.TYPE_NULL);
            } else {
                mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

                Class<EditText> clazz = EditText.class;
                Method method;

                try {
                    method = clazz.getMethod("setShowSoftInputOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    method = clazz.getMethod("setSoftInputShownOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void initEvent() {
        mPhoneEdt.addTextChangedListener(this);
        mCodeEdt.addTextChangedListener(this);
        mEmailEdt.addTextChangedListener(this);

        mPhoneEdt.setOnMyFocusChangeListener(this);
        mCodeEdt.setOnMyFocusChangeListener(this);
        mEmailEdt.setOnMyFocusChangeListener(this);
        mSubmitBtn.setOnClickListener(this);

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof RCBindingFragment) {
            mActivity.setTitle(R.string.binding);
        }
    }

    @Override
    public void requestDatas() {
        mMailmap = new HashMap();
        mMailmap.put("@163.com", "http://smart.mail.163.com/");
        mMailmap.put("@yahoo.com", "https://login.yahoo.com/");
        mMailmap.put("@126.com", "http://smart.mail.126.com/");
        mMailmap.put("@sina.com", "http://mail.sina.cn/");
        mMailmap.put("@21cn.com", "http://mail.21cn.com/");
        mMailmap.put("@qq.com", "https://mail.qq.com/");
        mMailmap.put("@sohu.com", "https://m.mail.sohu.com/");
        mMailmap.put("@189.cn", "https://wap.189.cn/");
        mMailmap.put("@139.com", "http://mail.10086.cn/");


    }

    private boolean isGetCode;
    private boolean isSubmit;
    private boolean isEmailGet;

    private CountDownTimer mCountDownTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mTvVerficode.setEnabled(false);
            mTvVerficode.setTextColor(getResources().getColor(R.color.common_color_c8_d5d7dc));
            mTvVerficode.setText(String.format("%d秒后重发", millisUntilFinished / 1000));

        }


        @Override
        public void onFinish() {
            isEle = true;
            if (mPhoneEdt.getText().toString().length() == 11) {
                mTvVerficode.setEnabled(true);
                mTvVerficode.setTextColor(getResources().getColor(R.color.common_color_c1_337cff));
                mTvVerficode.setText(mActivity.getResources().getString(R.string.reget_code));
            } else {
                mTvVerficode.setText(mActivity.getResources().getString(R.string.reget_code));
            }

        }
    };

    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i != R.id.et_phone && i != R.id.et_code) {
            if (mNumKeyboard.getVisibility() == View.VISIBLE) {
                mNumKeyboard.setVisibility(View.INVISIBLE);
            }

        }

        if (i == R.id.et_phone) {
            mNumKeyboard.setVisibility(View.VISIBLE);
        }
        if (i == R.id.et_code) {
            mNumKeyboard.setVisibility(View.VISIBLE);
        }

        if (i != R.id.et_email) {
            hideSoftKeyBoard(mEmailEdt);
        }
        if (i == R.id.tv_verificode) {
            mTilPhone.setStateNormal();//请求超时的时候 再次点击 让它恢复正常样式
            isEle = false;//
            isGetCode = true;
            mPhoneEdt.clearFocus();
            isGetCode = false;
            //            mTimeCount = new TimeCount(60000, 1000, mTvVerficode, getResources().getString(R.string.reget_code));
            //            mTimeCount.start();
            Map<String, String> codeMap = new HashMap();
            codeMap.put("mobile", mPhoneEdt.getText().toString());
            codeMap.put("smsType", "1");
            showProgressDialog(mActivity.getString(R.string.loadding));
            NoHttpUtils.httpPost(UserCenterConstant.URL_GET_SMS_VERIFICATION, codeMap, mResponseListener, 0);

            mCountDownTimer.start();

        } /*else if (i == R.id.tv_bindlink) {
            isEmail = false;
            isEmailGet = true;
            mEmailEdt.clearFocus();
            isEmailGet = false;
            mTimeCount = new TimeCount(60000, 1000, mTvBindLink, getResources().getString(R.string.reget_connect));
            mTimeCount.start();
            Map<String, String> mailMap = new HashMap<>();
            mailMap.put("email", mEmailEdt.getText().toString());
            showProgressDialog(mActivity.getString(R.string.loadding));
            NoHttpUtils.httpPost(UserCenterConstant.URL_SEND_EMAIL, mailMap, mResponseListener, 1);

        }*/ else if (i == R.id.btn_submit) {
            isEmailGet = true;
            mCodeEdt.clearFocus();
            isEmailGet = false;
            Map<String, String> smsCodeMap = new HashMap();
            smsCodeMap.put("mobile", mPhoneEdt.getText().toString());
            smsCodeMap.put("verifycode", mCodeEdt.getText().toString());
            showProgressDialog(getResources().getString(R.string.submiting));
            NoHttpUtils.httpPost(UserCenterConstant.URL_CHECK_VERIFY_CODE, smsCodeMap, mResponseListener, 2);

        } else if (i == R.id.tv_binding) {//判断是否含有邮箱特别字段
            Iterator iter = mMailmap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                String url = (String) entry.getValue();
                if (mEmailEdt.getText().toString().trim().endsWith(key)) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(url);
                    intent.setData(content_url);
                    startActivity(intent);
                }
            }

        } else if (i == R.id.rl_else) {
            if (mPhoneEdt.isFocusable()) {
                mPhoneEdt.clearFocus();
            }
            if (mCodeEdt.isFocusable()) {
                mCodeEdt.clearFocus();
            }
            if (mEmailEdt.isFocusable()) {
                mEmailEdt.clearFocus();
            }
            InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            if (mNumKeyboard.getVisibility() == View.VISIBLE) {
                mNumKeyboard.setVisibility(View.INVISIBLE);
            }

        }
    }

    private NoHttpUtils.OnResponseListener mResponseListener = new NoHttpUtils.OnResponseListener() {

        private String mEmailCode;

        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case 0:
                    if ("0".equals(commonClass.getCode())) {
                        //获得短信
                    } else {
                        mTilPhone.setStateWrong(commonClass.getMsg());
                    }
                    break;
                case 1:
                    if ("0".equals(commonClass.getCode())) {
                        //邮箱收到一个连接
                        mEmailCode = (String) commonClass.getData();
                        mBindingTxt.setVisibility(View.VISIBLE);
                    } else {
                        mTilEmail.setStateWrong(commonClass.getMsg());
                        mViewEmail.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                    }
                    break;
                case 2:
                    if ("0".equals(commonClass.getCode())) {
                        Map<String, String> bindEmailMap = new HashMap();
                        bindEmailMap.put("emailCode", mEmailCode);
                        //                        NoHttpUtils.httpPost(UserCenterConstant.URL_CHECK_EMAIL_BIND, bindEmailMap, mResponseListener, 3);
                        UserCenterCommon.getInstance().setMobile(mPhoneEdt.getText().toString().trim());
                        UserCenterCommon.getInstance().setEmail(mEmailEdt.getText().toString().trim());
                        EventBus.getDefault().post("RCBindingFragment");
                        //返回上一个界面
                        popFragment();
                    } else {
                        dismissProgressDialog();
                        mTilCode.setStateWrong(commonClass.getMsg());
                        mViewCode.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                    }
                    break;
                case 3:
                    //                    if ("0".equals(commonClass.getCode())) {
                    //                        UserCenterCommon.getInstance().setMobile(mPhoneEdt.getText().toString().trim());
                    //                        UserCenterCommon.getInstance().setEmail(mEmailEdt.getText().toString().trim());
                    //                        EventBus.getDefault().post("RCBindingFragment");
                    //                        //返回上一个界面
                    //                        popFragment();
                    //                    } else {
                    //                        toast(commonClass.getMsg());
                    //                    }
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            toast(result);
        }

        @Override
        public void onFinish(int what) {
            //            if (what != 2) {
            dismissProgressDialog();
            //            }
        }
    };

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(mPhoneEdt.getText().toString().trim()) &&
                !TextUtils.isEmpty(mCodeEdt.getText().toString().trim()) &&
                !TextUtils.isEmpty(mEmailEdt.getText().toString().trim()) && CheckUtils.isEmail(mEmailEdt.getText().toString().trim())) {
            mSubmitBtn.setEnabled(true);
            mSubmitBtn.setBackgroundResource(R.drawable.common_btn2_solid_selector);
        } else {
            mSubmitBtn.setEnabled(false);
            mSubmitBtn.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
        }

        //为11位就可以点击获取验证码
        if (mPhoneEdt.getText().toString().trim().length() == 11 && isEle) {
            mTvVerficode.setTextColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
            //            mTvVerficode.setClickable(true);
            mTvVerficode.setEnabled(true);
        } else {
            mTvVerficode.setTextColor(mActivity.getResources().getColor(R.color.common_color_c8_d5d7dc));
            //            mTvVerficode.setClickable(false);
            mTvVerficode.setEnabled(false);
        }

        //判断是否为邮箱
        if (CheckUtils.isEmail(mEmailEdt.getText().toString().trim()) && isEmail) {
            //            mTvBindLink.setTextColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
            //            mTvBindLink.setClickable(true);
            //            mTvBindLink.setEnabled(true);
        } else {
            //            mTvBindLink.setTextColor(mActivity.getResources().getColor(R.color.common_color_c8_d5d7dc));
            //            mTvBindLink.setClickable(false);
            //            mTvBindLink.setEnabled(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {


    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!isEmailGet) {
            int i = v.getId();
            if (i == R.id.et_phone) {
                if (hasFocus && !isGetCode) {
                    mTilPhone.setStateNormal();
                    mNumKeyboard.setVisibility(View.VISIBLE);
                    mNumKeyboard.setEditText((ClearEditText) v);
                    hideSoftKeyBoard(mEmailEdt);
                } else {
                    if (!(mPhoneEdt.getText().toString().trim().length() == 11)) {
                        mTilPhone.setStateWrong(mActivity.getString(R.string.phone_wrong));
                    }
                }

            } else if (i == R.id.et_code) {
                if (hasFocus) {
                    mTilCode.setStateNormal();
                    mViewCode.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                    mNumKeyboard.setVisibility(View.VISIBLE);
                    mNumKeyboard.setEditText((ClearEditText) v);
                    hideSoftKeyBoard(mEmailEdt);
                } else {
                    mViewCode.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c9_e8e9eb));
                    if (!TextUtils.isEmpty(mCodeEdt.getText().toString().trim())) {
                        if (!(mCodeEdt.getText().toString().trim().length() == 6)) {
                            mTilCode.setStateWrong(mActivity.getString(R.string.code_wrong));
                            mViewCode.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        } /*else {

                        }*/
                    }
                }

            } else if (i == R.id.et_email) {
                if (hasFocus) {
                    mTilEmail.setStateNormal();
                    mViewEmail.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                    if (mNumKeyboard.getVisibility() == View.VISIBLE) {
                        mNumKeyboard.setVisibility(View.INVISIBLE);
                    }

                } else {
                    mViewEmail.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c9_e8e9eb));
                    if (!TextUtils.isEmpty(mEmailEdt.getText().toString().trim())) {
                        if (!CheckUtils.isEmail(mEmailEdt.getText().toString().trim())) {
                            mTilEmail.setStateWrong(mActivity.getString(R.string.mail_wrong));
                            mViewEmail.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c11_ff1f1f));
                        } /*else {
                            mViewCode.setBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c9_e8e9eb));
                        }*/
                    }


                }
            }
        }

    }

    class TimeCount extends CountDownTimer {
        TextView mTextView;
        String   mString;

        public TimeCount(long millisInFuture, long countDownInterval, View view, String string) {
            super(millisInFuture, countDownInterval);
            mTextView = (TextView) view;
            mString = string;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTextView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c8_d5d7dc));
            mTextView.setClickable(false);
            mTextView.setText("(" + millisUntilFinished / 1000 + ")" + mActivity.getResources().getString(R.string.resend));
        }

        @Override
        public void onFinish() {
            mTextView.setText(mString);
            mTextView.setClickable(true);
            mTextView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
            if (mString.equals(mActivity.getResources().getString(R.string.reget_code))) {
                isEle = true;
            } else {
                isEmail = true;
            }

        }
    }

    @Override
    public void onDestroy() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        super.onDestroy();
        if (mNumKeyboard.getVisibility() == View.VISIBLE) {
            mNumKeyboard.setVisibility(View.INVISIBLE);
        }
        hideSoftKeyBoard(mEmailEdt);
    }
}
